import {
  reqMergeLocalCart,
  getNewCartGoods,
  reqFindCartList,
  reqInsertCart,
  reqDeleteCart,
  reqUpdateCartSku,
  reqCheckAllCart
} from '@/api/cart'

export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },

  getters: {
    // 计算有效商品列表 isEffective = true  filter
    effectiveList (state) {
      return state.list.filter(item => item.isEffective && item.stock > 0)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveTotal (state, getters) {
      return getters.effectiveList.reduce((sum, item) => item.count + sum, 0)
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    effectiveTotalPrice (state, getters) {
      return getters.effectiveList
        .reduce((sum, item) => item.count * item.nowPrice + sum, 0)
        .toFixed(2)
    },
    // 无效商品列表
    ineffectiveList (state) {
      return state.list.filter(item => !(item.isEffective && item.stock > 0))
    },
    // 已选择的列表
    selectedList (state, getters) {
      return getters.effectiveList.filter(item => item.selected)
    },
    // 已选择的商品总数
    selectedAllCounts (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    // 已选择的列表总价
    selectedAllPrice (state, getters) {
      return getters.selectedList
        .reduce((sum, item) => sum + item.count * item.nowPrice, 0)
        .toFixed(2)
    },
    // 是否全部选中
    isAllEffectSelected (state, getters) {
      return getters.effectiveList.every(item => item.selected)
    }
  },
  mutations: {
    addToCart (state, goods) {
      const findGoods = state.list.find(item => item.skuId === goods.skuId)
      if (findGoods) {
        findGoods.count += goods.count
      } else {
        state.list.unshift(goods)
      }
    },
    deleteCart (state, skuId) {
      const findIndex = state.list.findIndex(item => item.skuId === skuId)
      console.log(findIndex)
      if (findIndex > -1) {
        state.list.splice(findIndex, 1)
      }
    },
    // 更新购物车商品信息
    updateCart (state, goods) {
      const sku = state.list.find(item => item.skuId === goods.skuId)
      if (sku) {
        sku.isEffective = goods.isEffective
        sku.nowPrice = goods.nowPrice
        sku.stock = goods.stock
      }
    },
    // 单个选中 & 取消选中
    checkEffect (state, { skuId, selected }) {
      state.list.find(item => item.skuId === skuId).selected = selected
    },
    // 全选 & 反选
    checkEffectAll (state, selected) {
      state.list.forEach(item => {
        if (item.isEffective) {
          item.selected = selected
        }
      })
    },
    // 更改数量
    changeCount (state, { skuId, count }) {
      state.list.find(item => item.skuId === skuId).count = count
    },
    setList (state, newList) {
      state.list = newList
    }
  },
  actions: {
    // 加入购物车
    // asyncAddToCart ({ commit, rootGetters }, goods) {
    //   return new Promise((resolve, reject) => {
    //     // 登录了
    //     if (rootGetters.getToken) {
    //       console.log('---已登录，发请求，异步操作---')
    //     } else {
    //       commit('addToCart', goods)
    //       resolve()
    //     }
    //   })
    // },
    async asyncAddToCart ({ commit, rootGetters, dispatch }, goods) {
      // 登录了
      if (rootGetters.getToken) {
        const { skuId, count } = goods
        await reqInsertCart({ skuId, count })
        // 重新拉取数据
        await dispatch('asyncUpdateCart')
      } else {
        commit('addToCart', goods)
      }
    },
    // 删除购物车商品
    // asyncDeleteCart ({ commit, rootGetters }, skuId) {
    //   return new Promise((resolve, reject) => {
    //     // 登录了
    //     if (rootGetters.getToken) {
    //       console.log('---已登录，发请求，异步操作---')
    //     } else {
    //       commit('deleteCart', skuId)
    //       resolve()
    //     }
    //   })
    // },
    async asyncDeleteCart ({ commit, rootGetters, dispatch }, skuId) {
      // 登录了
      if (rootGetters.getToken) {
        await reqDeleteCart([skuId])
        // 重新拉取数据
        await dispatch('asyncUpdateCart')
      } else {
        commit('deleteCart', skuId)
      }
    },
    // 更新商品信息
    asyncUpdateCart ({ commit, state, rootGetters }) {
      // 发送请求，更新购物车中所有的商品信息
      return new Promise((resolve, reject) => {
        // 登录了
        if (rootGetters.getToken) {
          reqFindCartList().then(({ result }) => {
            commit('setList', result)

            resolve()
          })
        } else {
          // 没有登录，需要发送请求进行商品信息更新
          const requestArr = state.list.map(item => {
            return getNewCartGoods(item.skuId)
          })

          Promise.all(requestArr).then(res => {
            res.forEach((item, index) => {
              commit('updateCart', {
                skuId: state.list[index].skuId,
                ...item.result
              })
            })

            resolve()
          })
        }
      })
    },
    // 单个选中 & 取消选中
    async asyncCheckEffect (
      { commit, rootGetters, dispatch },
      { skuId, selected }
    ) {
      // 登录了
      if (rootGetters.getToken) {
        await reqUpdateCartSku({
          skuId,
          selected
        })

        // 重新拉取数据
        await dispatch('asyncUpdateCart')
      } else {
        commit('checkEffect', { skuId, selected })
      }
    },
    // 全选 & 反选
    async asyncCheckEffectAll (
      { commit, getters, rootGetters, dispatch },
      selected
    ) {
      // 登录了
      if (rootGetters.getToken) {
        const skuIds = getters.effectiveList.map(item => item.skuId)
        await reqCheckAllCart({ selected, ids: skuIds })
        await dispatch('asyncUpdateCart')
      } else {
        commit('checkEffectAll', selected)
      }
    },
    // 更改数量
    async asyncChangeCount (
      { commit, rootGetters, dispatch },
      { skuId, count }
    ) {
      // return new Promise((resolve, reject) => {
      // 登录了
      if (rootGetters.getToken) {
        // 已登录，发请求 - 异步
        await reqUpdateCartSku({
          skuId,
          count
        })
        await dispatch('asyncUpdateCart')
      } else {
        commit('changeCount', { skuId, count })
        // resolve()
      }
      // })
    },
    // 合并购物车
    async asyncMergeLocalCart (context) {
      // 存储token后调用本地接口同步
      const cartList = context.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })

      await reqMergeLocalCart(cartList)

      // 合并成功后，从后端获取最新购物车列表替换本地
      await context.dispatch('asyncUpdateCart')
    }
  }
}
